package com.demo;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * <p>
 * <code>Person</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-06-06 14:26
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class Person1 {
    private static  Unsafe unsafe;
    private String[] table = {"1","2","3","4"};
    static{
        /*
            @CallerSensitive
            public static Unsafe getUnsafe() {
                Class var0 = Reflection.getCallerClass();
                if (var0.getClassLoader() != null) {
                    throw new SecurityException("Unsafe");
                } else {
                    return theUnsafe;
                }
            }
        */
        //直接这样用会抛出异常 因为person类的类加载器是app，不为null
//        unsafe = Unsafe.getUnsafe();
        //Unsafe类有一个属性Unsafe theUnsafe，可以通过反射获取
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Person1 person1 = new Person1();
        //数组中存储的对象的对象头大小
        int ns = unsafe.arrayIndexScale(String[].class);
        //数组中第一个元素的起始位置
        int base = unsafe.arrayBaseOffset(String[].class);
        //获取数组里面下标为1的元素 从内存拿而不是从工作空间拿缓存的值
        System.out.println(unsafe.getObject(person1.table,base+1*ns));

    }
}
